<!-- 费用核算 -->
<template>
  <div class="app-container">
    <div class="tabs">
      <px-radio-group v-model="activeName" class="tabSwitch" @change="tabSelectHandler">
        <!-- <px-radio-button v-has="`${item.permision}`" v-for="item in tabsOption" :key="item.name" :label="item.name">{{ item.label }}</px-radio-button> -->
        <px-radio-button label="electricity">电</px-radio-button>
        <px-radio-button label="water">水</px-radio-button>
        <px-radio-button label="ng">天然气</px-radio-button>
        <px-radio-button label="hotSteam">蒸汽/热水</px-radio-button>
        <px-radio-button label="gas">大宗气</px-radio-button>
        <px-radio-button label="diesel">柴油</px-radio-button>
      </px-radio-group>
      <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
        <px-form-item label="时间范围" style="width: 460px">
          <px-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-form-item>
          <px-button type="primary" @click="getList">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </px-form-item>
      </px-form>
    </div>
    <div class="mb-4">
      <px-button v-has="'ALL_ENERGY_COST_CHECK_ADD'" type="primary" @click="handleFn(null, 'ADD')">新增</px-button>
    </div>
    <div v-loading="tableLoading" class="table-content">
      <px-table
        :data="tableData"
        border
        show-overflow-tooltip
        height="calc(100vh - 405px)"
        :header-cell-style="{ background: '#e7eefb', color: '#000' }"
      >
        <px-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column prop="periodText" label="费用周期" align="center" min-width="80" />
        <px-table-column prop="version" label="周期时间" align="center" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.startTimeText }}-{{ scope.row.endTimeText }}</div>
          </template>
        </px-table-column>
        <px-table-column prop="calculateCost" label="计算费用" align="center" min-width="150" />
        <px-table-column prop="settlement" label="结算单费用" align="center" min-width="150" />
        <px-table-column label="结算单-计算费用" align="center" min-width="160">
          <template #default="scope">
            <div>{{ (scope.row.settlement - scope.row.calculateCost).toFixed(2) }}</div>
          </template>
        </px-table-column>
        <px-table-column label="结算凭证" align="center">
          <template #default="scope">
            <px-button link icon="Folder" type="primary" @click="viewFileVisible(scope.row)" />
          </template>
        </px-table-column>
        <px-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <px-tag :type="scope.row.auditType == 'N' ? 'warning' : 'success'" class="mx-1" effect="dark">
              {{ scope.row.auditType == "N" ? "待核算" : "已核算" }}
            </px-tag>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="查看" placement="top">
              <px-button v-has="'ALL_ENERGY_COST_CHECK_VIEW'" link icon="View" type="primary" @click="handleFn(scope.row, 'VIEW')" />
            </px-tooltip>
            <px-tooltip content="核算" placement="top">
              <px-button v-has="'ALL_ENERGY_COST_CHECK_CHECK'" link :icon="check_icon" type="primary" @click="handleFn(scope.row, 'EDIT')" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ALL_ENERGY_COST_CHECK_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
        <template #empty
          >flase
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </div>
    <px-dialog v-model="dialogVisible" :title="title" :disabled="handleType === 'VIEW'" width="700" align-center>
      <px-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
        <px-form-item v-if="handleType !== 'ADD'" label="能源" prop="kind">
          <div>{{ tableList.find(item => item.label === formData.kind) ? tableList.find(item => item.label === formData.kind).name : "" }}</div>
        </px-form-item>
        <px-form-item label="结算周期" prop="period" style="width: 380px">
          <px-date-picker
            v-model="formData.period"
            type="month"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime1"
            :disabled="handleType === 'VIEW'"
            placeholder="请选择结算周期"
          />
        </px-form-item>
        <px-form-item label="周期时间" prop="startTime" style="width: 380px">
          <px-date-picker
            v-model="dateFormRange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime2"
            :disabled="handleType === 'VIEW'"
            @change="dateChangeFn"
          />
        </px-form-item>
        <px-form-item v-if="handleType !== 'ADD'" label="计算费用" prop="calculateCost">
          <div>{{ formData.calculateCost }}元</div>
        </px-form-item>
        <px-form-item v-if="handleType !== 'ADD'" label="结算单费用" prop="settlement">
          <px-input v-model="formData.settlement" :disabled="handleType === 'VIEW'" placeholder="请输入">
            <template #append>万元</template>
          </px-input>
        </px-form-item>
        <px-form-item v-if="handleType !== 'ADD'" label="续费凭证" prop="file">
          <FileUpload
            :fileType="fileType"
            :fileSize="50"
            fileAccept=".pdf,.jpg,.png,.jpeg"
            fileTypeValue="pdf,jpg,png,jpeg"
            :isPreview="Boolean(true)"
            :fileData="{ moduleName: 'ACCOUNTING_MANAGE' }"
            :fileList="formData.file"
            @changeFileList="changeFileList"
            @saveFileStatus="saveFileStatus"
          />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="dialogVisible = false">取消</px-button>
          <px-button v-if="handleType !== 'VIEW'" type="primary" @click="confirmFn"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
    <px-dialog v-model="dialogFilesVisible" title="结算凭证" width="600" align-center>
      <px-table :data="fileData" border show-overflow-tooltip :header-cell-style="{ background: '#e7eefb', color: '#000' }">
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="originalName" label="文件名" align="center" min-width="160">
          <template #default="scope">
            <px-button type="primary" text @click="handlePreview(scope.row)">{{ scope.row.originalName }}</px-button>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="下载" placement="top">
              <px-button link icon="Download" type="primary" @click="fileDownload(scope.row)" />
            </px-tooltip>
            <!-- <px-tooltip content="删除" placement="top">
              <px-button link icon="Delete" type="danger" @click="fileDelete(scope.row)" />
            </px-tooltip> -->
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_COST_CALCULATE"
});
import { PxMessage, PxMessageBox } from "px-ui";
import { useRouter } from "vue-router";
// import FileUpload from "./components/fileUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { ref, reactive, computed, toRefs, onMounted, nextTick, getCurrentInstance } from "vue";
import { getCheckList, updateCheck, viewCheck, delCheck, checkConfim } from "@/api/energy/costCheck";
import { deleteFileDms } from "@/api/common";
import check_icon from "@/assets/svg/energy/check_icon.svg";

const { proxy }: any = getCurrentInstance();

const router = useRouter();

const tableLoading = ref(false);
const dialogVisible = ref(false);
const dialogFilesVisible = ref(false);
const fileUploadVisible = ref(false);
const formData = ref<any>({});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const defaultTime1: Date = new Date(2000, 1, 1, 0, 0, 0);
const defaultTime2: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 0, 0, 0)];

const activeName = ref("electricity");

const tableList = [
  {
    name: "电",
    label: "electricity"
  },
  {
    name: "水",
    label: "water"
  },
  {
    name: "天然气",
    label: "ng"
  },
  {
    name: "蒸汽/热水",
    label: "hotSteam"
  },
  {
    name: "大宗气",
    label: "gas"
  },
  {
    name: "柴油",
    label: "diesel"
  }
];

const paramsActiveName = computed(() => {
  return activeName.value;
});

const handleType = ref("ADD");
const title = ref("新增");
const dateRange = ref([]);
const dateFormRange = ref([]);
const fileType = ref("add");

const state = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // startDate: proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
    startDate: "",
    endDate: "",
    kind: paramsActiveName
  },
  tableData: [],
  fileStatusFlag: false,
  fileData: [],
  rules: {
    period: [{ required: true, message: "请选择结算周期", trigger: "blur" }],
    startTime: [{ required: true, message: "请选择周期时间", trigger: "blur" }],
    settlement: [{ required: true, message: "请输入结算单费用", trigger: "blur" }]
  },
  total: 0
});
const { queryParams, tableData, fileData, fileStatusFlag, rules, total } = toRefs(state);

const uploadRef = ref(null);

const tabSelectHandler = (selectName: string) => {
  activeName.value = selectName;
  getList();
};

const dateChangeFn = val => {
  formData.value.startTime = val ? val[0] : "";
  formData.value.endTime = val ? val[1] : "";
};

/** 列表 */
const getList = async () => {
  tableLoading.value = true;
  const res: any = await getCheckList(proxy.addDateRange(queryParams.value, dateRange.value, "startDate", "endDate"));
  res?.data?.forEach(i => {
    i.endTimeText = i.endTime?.split(" ")[0];
    i.startTimeText = i.startTime.split(" ")[0];
    i.periodText = i.period.split(" ")[0];
  });
  tableData.value = res.data || [];
  total.value = res?.total;
  tableLoading.value = false;
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.$refs["queryRef"].resetFields();
  getList();
};

const viewFileVisible = row => {
  dialogFilesVisible.value = true;
  fileData.value = row.file || [];
};

const handleUpload = () => {
  fileUploadVisible.value = true;
};

// 新的文件列表
const changeFileList = val => {
  // tableData.value = val;
  formData.value.file = val;
};

// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  console.log(val, "8888888888");
  fileStatusFlag.value = val;
  nextTick();
};

const handleFn = (row, type) => {
  handleType.value = type;
  fileType.value = type?.toLowerCase();
  title.value = type === "ADD" ? "新增" : type === "VIEW" ? "详情" : "核算";
  dialogVisible.value = true;
  nextTick(() => {
    proxy.$refs["formRef"].clearValidate();
  });
  nextTick(() => {
    if (type === "ADD") {
      formData.value = {};
      dateFormRange.value = [];
    } else if (type === "VIEW") {
      formData.value = Object.assign({}, row);
      dateFormRange.value = [row.startTime, row.endTime];
    } else {
      viewCheck({ id: row.id })
        .then((res: any) => {
          formData.value = Object.assign({}, res);
          dateFormRange.value = [res.startTime, res.endTime];
        })
        .catch(e => console.log(e));
    }
  });
};

// 预览
const handlePreview = row => {
  if (row != null) {
    const { id, fileName, moduleName, fileType: type = "" } = row;
    // doc 暂不支持预览
    const allowType = ["txt", "docx", "xls", "xlsx", "pdf", "png", "jpg", "jpeg", "mp4"];
    if (!allowType.includes(type)) {
      PxMessage.error("暂不支持该格式文件的预览");
      return;
    }
    const path = "/fullScreen/preview";
    const query = { id, fileName, moduleName, type };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    PxMessage.error("没有可以预览的文件");
  }
};

// 文档删除
const fileDelete = async (row: any) => {
  await deleteFileDms({ id: row.id });
  PxMessage.success("文档删除成功");
};

// 文档下载
const fileDownload = (row: any) => {
  const params = {
    id: row.id,
    fileName: row.fileName,
    moduleName: "ACCOUNTING_MANAGE"
  };
  proxy.download("post", "/sharing/api/v1/file/download", params, row.originalName);
};

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  PxMessageBox.confirm(`是否确认删除数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delCheck({ id: row.id });
      PxMessage.success("删除成功");
      getList();
    })
    .catch(() => {});
};

/** 保存按钮操作 */
const confirmFn = () => {
  proxy.$refs["formRef"].validate(valid => {
    if (!valid) return;
    // PxMessageBox.confirm(`确定保存吗？`, "温馨提示", {
    //   confirmButtonText: "确定",
    //   cancelButtonText: "取消",
    //   type: "warning",
    //   draggable: true
    // })
    //   .then(async () => {

    //   })
    //   .catch(() => { });
    const params = Object.assign({}, formData.value);
    if (handleType.value === "ADD") {
      params.kind = paramsActiveName.value;
      updateCheck(proxy.addDateRange(params, dateFormRange.value)).then(res => {
        PxMessage.success("保存成功");
        dialogVisible.value = false;
        getList();
      });
    } else {
      checkConfim(proxy.addDateRange(params, dateFormRange.value)).then(res => {
        PxMessage.success("核算完成");
        dialogVisible.value = false;
        getList();
      });
    }
  });
};

onMounted(async () => {
  await getList();
});
</script>

<style lang="scss" scoped>
.hidden {
  display: none;
}

.tabs {
  /*
    * tab样式
    */
  .tabSwitch {
    padding: 4px;
    margin-bottom: 16px;
    background-color: #f4f4f4;
    border-radius: 4px;

    :deep(.px-radio-button__inner) {
      background-color: #f4f4f4;
      border: none;
    }

    :deep(.is-active) {
      border: none;

      .px-radio-button__inner {
        background-color: var(--px-color-primary);
        border-radius: 4px;
      }
    }
  }
}

.px-form-item {
  .px-select {
    width: 100%;
  }

  .px-input {
    width: 100%;
  }

  :deep(.px-date-editor) {
    width: 100%;
  }
}

.upload-form-item {
  display: flex;
  flex-flow: column nowrap;
}
</style>
